// pages/write/detail.js
var app = getApp();
// var WxParse = require('../../utils/wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    modalName:'',
    id: '',
    detail: '',
    liked: false,
    likecount: '',
    readcount: '',
    content: '',
    detailContetnt:'',
    arr: '',
    StartTime: '',
    EndTime: '',
    imgss: '',
    openid: '',
    isDuaration: true,
    writelist:[],
    category:'',
    follows: null,
    follow_count: 0,
    follow_user_id: 0,
    tuijian: 0,
    isShowkefu: true,
    // userImg:null
  },
  previewImagess(e) {
    var current = e.target.dataset.src;
    console.log(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: this.data.imgss
    })

  }, //预览图片

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    setTimeout(() => {
      this.setData({
        isDuaration: false
      })
    }, 1000)
    var that = this;
    var opid = wx.getStorageSync('user_new');
    var follow_user_id = '';

    //options['scene'] = '1133_1'

    if (options.scene == undefined) {
      var id = options.id

      if (options.follow_user_id != undefined) {
        follow_user_id = options.follow_user_id
        this.setData({
          follow_user_id: options.follow_user_id
        })
        wx.setStorageSync('referrer', follow_user_id)
      }
    } else {
      var scene = options.scene;
      scene = scene.split('_')

      if (scene.length > 1) {
        follow_user_id = scene[1]
      }
      var id = scene[0];
    }

    this.followAndList(id, follow_user_id)
    this.tuijian()
    that.setData({
      id: id,
      openid: opid
    })
    that.read();
    that.detail();
  },
  detail() {
    var WxParse = require('../../utils/wxParse/wxParse.js');
    var that = this;
    var like = that.data.liked;
    var id = that.data.id;

    var opid = wx.getStorageSync('user_new');
    app.core('get', 'xiaochengxu_article_detail/id/' + id + '/openid/' + opid + '', {}, (res => {
      var arr = res.data;
      console.log(arr,111);
      var like = arr.like;
      if (like == 1) {
        that.setData({
          liked: true
        })
      } else {
        that.setData({
          liked: false
        })
      }
      var commlist = res.data.xiaochengxu_article_comment;

      var commentarr = [];
      for (var i = 0; i < commlist.length; i++) {
        if (commlist[i].p_comment_id == 0) {
          commentarr.push(commlist[i])
        }

      }
      var imglist = arr.album;

      that.setData({
        detail: arr,
        arr: commentarr,
        imgss: arr.album_txt,
        category: arr.category
      })


      var detail_desc = res.data.content || '';
      that.setData({
        detail_desc: WxParse.wxParse('detail_desc', 'html', detail_desc, that, 5),
      })

      let category = this.data.category
      app.core('get', 'getMoreAboutArticle?category=' + category, '', (res) => {
        console.log(res.data)
        this.setData({
          writelist: res.data
        })
      })
      wx.hideLoading()
    }))

  }, // 详情

  btnlikes() {
    var that = this;
    var like = that.data.liked;
    var id = that.data.id;
    var opid = getApp().globalData.openid;

    if  (opid == undefined || opid == '') {
      wx.showModal({
        title: '提示',
        content: '本功能需要授权后才可使用，点击确定跳转到登录界面',
        success(res) {
          if (res.confirm) {
            setTimeout(() =>{
              that.toLogin()
            }, 500)
          } else if (res.cancel) {
          }
        }
      })

      return false
    }

    app.core('get', 'operate_like/article_id/' + id + '/open_id/' + opid + '', '', (res => {
      var islike = res.data.isLike;
      var likecount = res.data.count;

      if (islike == 0) {
        that.setData({
          liked: false,
          likecount: likecount
        })
        wx.showToast({
          title: '取消点赞',
          icon: 'none',
          duration: 1000
        })
      } else if (islike == 1) {
        that.setData({
          liked: true,
          likecount: likecount
        })
        wx.showToast({
          title: '点赞成功',
          icon: 'none',
          duration: 1000
        })
      }
    }))
  },
  //点赞
  read() {
    var that = this;
    var id = that.data.id;
    var opid = wx.getStorageSync('user_new');
    app.core('get', 'operate_vist/id/' + id + '', '', (res => {
      console.log(res, 'res')
      that.setData({
        readcount: res.data.count,

      })
    }))
  },
  //访问

  priveimg(e) {
    console.log(e)
    var img = e.currentTarget.dataset.img;
    var arr = [];
    arr.push(img)
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },
  //预览图片
  /**

   *
   /**
   *
   * 生命周期函数--监听页面初次渲染完成
   */

  input(e) {
    this.setData({
      content: e.detail.value
    })

  },
  submit() {
    var that = this;
    var content = that.data.content;
    // var p_comment_id= ''; // 评论文章的id
    var opids = wx.getStorageSync('user_new'); //存入全局变量
    var opid = getApp().globalData.openid;
    console.log(opid, '存储的obj啊');
    // var opid = wx.getStorageSync('user').openid;
    var tid = that.data.id;

    if  (opid == undefined || opid == '') {
      wx.showModal({
        title: '提示',
        content: '本功能需要授权后才可使用，点击确定跳转到登录界面',
        success(res) {
          if (res.confirm) {
            setTimeout(() =>{
              that.toLogin()
            }, 500)
          } else if (res.cancel) {
          }
        }
      })

      return false
    }

    if (content == '') {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none',
        duration: 1000
      })
    } else {
      console.log(content)
      wx.showLoading({
        title: '提交中',
      })
      app.core('post', 'create_article_comment', {

        open_id: opid,
        article_id: tid,
        p_xiaochengxu_user_id: 0,
        comment: content,
        p_comment_id: 0,

      }, (res => {
        console.log(res)
        if (res.resultCode == 200) {
          wx.hideLoading()
          wx.showToast({
            title: '评论成功',
            icon: 'none',
            duration: 1000
          })
          that.setData({
            'content': ''
          })
          setTimeout(function() {
            var sid = that.data.id;

            var options = {
              id: sid
            }
            that.onLoad(options)
          }, 1000)
        }
      }))

    }
  },
  share(e) {
    var id = this.data.id;
    console.log(id)
    wx.navigateTo({
      url: `/pages/writeposter/index?id=${id}`
    })
  },
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var timestamp = Date.parse(new Date()); //进入页面的时间戳
    var Stimestamp = timestamp / 1000;
    this.setData({
      StartTime: Stimestamp
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var timestamp = Date.parse(new Date()); //离开页面的的时间戳
    var Etimestamp = timestamp / 1000;
    this.setData({
      EndTime: Etimestamp
    });
    app.core('post', 'create_data_statistics', {
          // data 部分
          'type': 3,
          'visit_time': this.data.EndTime - this.data.StartTime,
          'read_id': this.data.id,
          'open_id': wx.getStorageSync('user_new')
        }, (res) => {
          console.log(res)
        },
        (err) => {
          console.log(err)
        }
    )
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    var that = this;
    var id = that.data.id
    var title = that.data.detail.title;
    var imgUrl = that.data.imgss[0];
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var user = wx.getStorageSync('user')
    var follow_user_id = 0
    if (user && user.user_id) {
      follow_user_id = user.user_id
    }
    return {
      title: title, // 默认是小程序的名称(可以写slogan等)
      path: 'pages/write/detail?id=' + id + '&follow_user_id=' + follow_user_id,
      imageUrl: imgUrl, //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function(res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          wx.showToast({
            title: '转发成功',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function() {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
          wx.showToast({
            title: '已取消转发',
            icon: 'none',
            duration: 1000
          })
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
          wx.showToast({
            title: '转发失败',
            icon: 'none',
            duration: 1000
          })
        }
      },
    }
  },

  toLogin: function () {
    wx.reLaunch({
      url: '/pages/member/index?redirect=' + encodeURIComponent('/pages/write/detail?id=' + this.data.id)
    })

    return false
  },

  followAndList: function(id, follow_user_id) {
    var open_id = wx.getStorageSync('user_new');
    app.core('get', 'user/followByType', {id: id, open_id: open_id, follow_user_id: follow_user_id, type: 'write'}, (res) => {
      this.setData({
        follows: res.data.follows,
        follow_count: res.data.count,
      })
    })
  },

  tuijian() {
    var that = this;
    var setid = app.globalData.cityCode;
    app.core('get', 'write/getRecommendHouses?siteId=' + setid + '&id=' + this.data.id + '&open_id=' + this.data.openid, {},
        (res) => {
          that.setData({
            tuijian: res.data
          })
        }
    )
  },

  handleFollow(e) {
    wx.navigateTo({
      url: '/pages/loupan/follow/index?id=' + this.data.id + '&type=write'
    })
  },

  handleReport(e) {
    wx.navigateTo({
      url: '/pages/report/index?id=' + this.data.id + '&type=write&title=' + encodeURIComponent(this.data.detail.title)
    })
  },

  toChat(e) {
    var that = this
    var opid = wx.getStorageSync('user_new');
    var id = e.currentTarget.dataset.id;
    if (!opid){
      wx.showModal({
        title: '提示',
        content: '授权后可以查看楼盘信息，方便本平台提供更多优质服务',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.showModal()
          } else if (res.cancel) {

          }
        }
      })
    }else if(opid == id){
      wx.showToast({
        title: '不可给自己留言',
      })
    }else{
      wx.navigateTo({
        url: '../adviser/chat/chat?id=' + id,
      })
    }
  },


  showModal(e) {
    this.setData({
      modalName: 'DialogModal1'
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  getUserInfo: function (e) {
    console.log(e)
    var vm = this;
    var UserInfo = e.detail.userInfo
    // wx.setStorageSync('userInfo', e.detail.userInfo)
    wx.login({
      success(res) {
        console.log(res)
        if (res.code) {
          var userCode = res.code;
          var referrer = wx.getStorageSync('referrer')
          app.core('post', 'create_xcx_user', {
                'nickname': UserInfo.nickName,
                'headpic': UserInfo.avatarUrl,
                'js_code': userCode,
                'referrer': referrer
              }, (res) => {
                console.log(res)
                // return false
                console.log("open_id" + res.data.open_id);
                wx.setStorageSync('userInfo', e.detail.userInfo);
                console.log(wx.getStorageSync('userInfo'));
                wx.setStorageSync('user_new', res.data.open_id);
                wx.setStorageSync('sessionKey', res.sessionKey);
                console.log(wx.getStorageSync('user_new'))

                getApp().globalData.openid = res.data.open_id

                vm.setData({
                  userInfo: e.detail.userInfo,
                  hasUserInfo: true,
                  isMain: true,
                  isPower: wx.getStorageSync('user_new')
                });
                wx.hideLoading()
                vm.setData({
                  modalName: null
                })
              },
              (err) => {
                console.log(err)
              }
          )

        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });


  },

})
